{% extends "base.html" %}

{% block title %}仪表盘{% endblock %}

{% block content %}
<div class="container">
    <div class="toolbar">
        <h2>同步目录管理</h2>
        <div>
            <a href="{{ url_for('add_sync_dir') }}" class="btn btn-primary">
                <i class="bi bi-plus-circle"></i> 添加同步目录
            </a>
            <a href="{{ url_for('sync_history') }}" class="btn btn-secondary">
                <i class="bi bi-clock-history"></i> 查看同步历史
            </a>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="card fade-in">
        <div class="card-header">
            <h5><i class="bi bi-bar-chart"></i> 同步概览</h5>
        </div>
        <div class="card-body">
            <div class="stats-container">
                <div class="stat-card">
                    <div class="stat-icon" style="background-color: var(--primary-light);">
                        <i class="bi bi-folder2"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">{{ sync_dirs|length }}</div>
                        <div class="stat-label">同步目录</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon" style="background-color: var(--success-color);">
                        <i class="bi bi-check-circle"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">{{ sync_dirs|selectattr('sync_status', 'equalto', 'active')|list|length }}</div>
                        <div class="stat-label">正常同步</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon" style="background-color: var(--warning-color);">
                        <i class="bi bi-exclamation-triangle"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">{{ sync_dirs|selectattr('sync_status', 'equalto', 'pending')|list|length }}</div>
                        <div class="stat-label">等待同步</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon" style="background-color: var(--danger-color);">
                        <i class="bi bi-x-circle"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">{{ sync_dirs|selectattr('sync_status', 'equalto', 'error')|list|length }}</div>
                        <div class="stat-label">同步错误</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 同步目录列表 -->
    <div class="card mt-4 fade-in">
        <div class="card-header">
            <h5><i class="bi bi-folder2-open"></i> 同步目录</h5>
        </div>
        <div class="card-body">
            {% if sync_dirs %}
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>本地路径</th>
                            <th>FTP路径</th>
                            <th>状态</th>
                            <th>上次同步</th>
                            <th>同步策略</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for dir in sync_dirs %}
                        <tr>
                            <td>
                                <a href="{{ url_for('browse_local', dir_id=dir.id) }}" title="浏览本地目录">
                                    <i class="bi bi-folder2"></i> {{ dir.local_path }}
                                </a>
                            </td>
                            <td>
                                <a href="{{ url_for('browse_ftp', dir_id=dir.id) }}" title="浏览FTP目录">
                                    <i class="bi bi-cloud"></i> {{ dir.ftp_host }}:{{ dir.ftp_path }}
                                </a>
                            </td>
                            <td>
                                <span class="sync-status badge {% if dir.sync_status == 'active' %}bg-success
                                            {% elif dir.sync_status == 'pending' %}bg-warning
                                            {% elif dir.sync_status == 'error' %}bg-danger
                                            {% else %}bg-secondary{% endif %}"
                                      data-sync-dir-id="{{ dir.id }}">
                                    {% if dir.sync_status == 'active' %}正常同步
                                    {% elif dir.sync_status == 'pending' %}等待同步
                                    {% elif dir.sync_status == 'error' %}同步错误
                                    {% else %}未知状态{% endif %}
                                </span>
                            </td>
                            <td>{{ dir.last_sync if dir.last_sync else '从未同步' }}</td>
                            <td>
                                <div class="strategy-container">
                                    <button class="strategy-btn" type="button" onclick="openStrategyModal('{{ dir.id }}')">
                                        {% if dir.sync_strategy == 'local_priority' %}
                                            <span class="badge bg-primary">本地优先</span>
                                        {% elif dir.sync_strategy == 'server_priority' %}
                                            <span class="badge bg-info">服务器优先</span>
                                        {% elif dir.sync_strategy == 'time_size' %}
                                            <span class="badge bg-secondary">时间大小比较</span>
                                        {% elif dir.sync_strategy == 'none' %}
                                            <span class="badge bg-warning">请选择策略</span>
                                        {% else %}
                                            <span class="badge bg-secondary">未知</span>
                                        {% endif %}
                                    </button>
                                </div>
                            </td>
                            <td>
                                <div class="btn-group">
                                    <a href="{{ url_for('sync_now', dir_id=dir.id) }}" class="btn btn-sm btn-primary" title="立即同步">
                                        <i class="bi bi-arrow-repeat"></i>
                                    </a>
                                    <a href="{{ url_for('force_sync', dir_id=dir.id) }}" class="btn btn-sm btn-warning" title="强制同步">
                                        <i class="bi bi-lightning"></i>
                </a>
                                    <a href="{{ url_for('delete_sync_dir', dir_id=dir.id) }}" 
                                       class="btn btn-sm btn-danger" 
                                       onclick="return confirm('确定要删除这个同步目录吗？')" title="删除">
                                        <i class="bi bi-trash"></i>
                                    </a>
                    </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
                    </div>
            {% else %}
            <div class="text-center">
                <p>还没有添加任何同步目录</p>
                <a href="{{ url_for('add_sync_dir') }}" class="btn btn-primary">
                    <i class="bi bi-plus-circle"></i> 添加同步目录
                </a>
            </div>
            {% endif %}
        </div>
    </div>

    <!-- 策略选择模态框 -->
    <div id="strategyModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h4>选择同步策略</h4>
                <span class="close-modal" onclick="closeStrategyModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="strategy-options">
                    <a class="strategy-option local-priority" id="local-priority-link" href="#">
                        <div class="strategy-icon">
                            <i class="bi bi-laptop"></i>
                        </div>
                        <div class="strategy-info">
                            <span class="badge bg-primary">本地优先</span>
                            <p>本地文件优先于服务器</p>
                        </div>
                    </a>
                    <a class="strategy-option server-priority" id="server-priority-link" href="#">
                        <div class="strategy-icon">
                            <i class="bi bi-cloud-upload"></i>
                        </div>
                        <div class="strategy-info">
                            <span class="badge bg-info">服务器优先</span>
                            <p>服务器文件优先于本地</p>
                        </div>
                    </a>
                    <a class="strategy-option time-size" id="time-size-link" href="#">
                        <div class="strategy-icon">
                            <i class="bi bi-clock-history"></i>
                        </div>
                        <div class="strategy-info">
                            <span class="badge bg-secondary">时间大小比较</span>
                            <p>根据修改时间和大小决定</p>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 实时同步活动（已移到底部） -->
    {% if sync_dirs|selectattr('sync_status', 'equalto', 'active')|list|length > 0 %}
    <div class="sync-activities mt-4">
        <h6><i class="bi bi-activity"></i> 实时同步活动</h6>
        <div id="syncActivitiesContainer">
            {% for dir in sync_dirs %}
            {% if dir.sync_status == 'active' %}
            <div class="sync-group" data-dir-path="{{ dir.local_path }}">
                <div class="sync-group-header">
                    <h6><i class="bi bi-folder"></i> {{ dir.local_path }}</h6>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>文件</th>
                                <th>操作</th>
                                <th>方向</th>
                                <th>路径</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% if sync_history[dir.local_path] %}
                                {% for item in sync_history[dir.local_path] %}
                                <tr class="sync-record" data-timestamp="{{ item.timestamp }}">
                                    <td>{{ item.timestamp }}</td>
                                    <td class="truncate-text" title="{{ item.filename }}">{{ item.filename }}</td>
                                    <td>
                                        <span class="badge {% if item.operation == 'create' or item.operation == 'create_dir' %}bg-success
                                                     {% elif item.operation == 'delete' or item.operation == 'delete_dir' %}bg-danger
                                                     {% elif item.operation == 'modify' %}bg-warning
                                                     {% elif item.operation == 'move' or item.operation == 'move_dir' %}bg-info
                                                     {% else %}bg-secondary{% endif %}">
                                            {{ item.operation }}
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge {% if item.direction == 'local_to_server' %}bg-primary{% else %}bg-info{% endif %}">
                                            {{ '上传' if item.direction == 'local_to_server' else '下载' }}
                                        </span>
                                    </td>
                                    <td class="truncate-text" title="{{ item.path }}">{{ item.path }}</td>
                                </tr>
                                {% endfor %}
                            {% else %}
                                <tr>
                                    <td colspan="5" class="text-center text-muted">暂无同步记录</td>
                                </tr>
                            {% endif %}
                        </tbody>
                    </table>
                </div>
            </div>
            {% endif %}
            {% endfor %}
        </div>
    </div>
    {% endif %}
</div>

<!-- Socket.IO -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>

<script>
let socket = null;
let isConnecting = false;
let reconnectTimer = null;
let currentDirId = null;

// 初始化Socket.IO连接
function initializeSocket() {
    if (isConnecting || (socket && socket.connected)) {
        console.log('已经存在连接或正在连接中，跳过初始化');
        return;
    }

    isConnecting = true;
    console.log('初始化新的WebSocket连接...');

    // 如果存在旧的连接，先断开
    if (socket) {
        console.log('断开旧的连接...');
        socket.disconnect();
        socket = null;
    }

    // 创建新的连接
    socket = io('http://127.0.0.1:5011', {
        transports: ['websocket'],
        upgrade: false,
        reconnection: true,
        reconnectionAttempts: 5,
        reconnectionDelay: 1000,
        forceNew: true,
        timeout: 10000
    });

    // 连接事件处理
    socket.on('connect', function() {
        console.log('WebSocket连接成功');
        isConnecting = false;
        clearTimeout(reconnectTimer);
    });

    socket.on('disconnect', function(reason) {
        console.warn('WebSocket连接断开，原因:', reason);
        isConnecting = false;
        scheduleReconnect();
    });

    socket.on('connect_error', function(error) {
        console.error('WebSocket连接错误:', error);
        isConnecting = false;
        scheduleReconnect();
    });

    // 监听同步历史更新
    socket.on('sync_history', function(data) {
        console.log('收到同步历史更新:', data);
        const historyItem = data.history_item;
        
        // 找到对应目录的同步组
        const dirGroup = document.querySelector(`.sync-group[data-dir-path="${historyItem.local_path}"]`);
        if (!dirGroup) {
            console.warn('找不到对应的目录组:', historyItem.local_path);
            return;
        }
        
        // 找到表格体
        const tbody = dirGroup.querySelector('tbody');
        if (!tbody) {
            console.warn('找不到表格体');
            return;
        }
        
        // 移除"暂无同步记录"的提示行（如果存在）
        const emptyRow = tbody.querySelector('tr td[colspan="5"]');
        if (emptyRow) {
            emptyRow.parentElement.remove();
        }

        // 检查新记录是否在一分钟内
        const recordTime = new Date(historyItem.timestamp);
        const now = new Date();
        if (now - recordTime > 60000) { // 如果记录超过1分钟，不显示
            return;
        }
        
        // 创建新的行
        const tr = document.createElement('tr');
        tr.className = 'sync-record new-sync-item';
        tr.dataset.timestamp = historyItem.timestamp;
        tr.innerHTML = `
            <td>${historyItem.timestamp}</td>
            <td class="truncate-text" title="${historyItem.filename}">${historyItem.filename}</td>
            <td>
                <span class="badge ${getOperationClass(historyItem.operation)}">
                    ${historyItem.operation}
                </span>
            </td>
            <td>
                <span class="badge ${historyItem.direction === 'local_to_server' ? 'bg-primary' : 'bg-info'}">
                    ${historyItem.direction === 'local_to_server' ? '上传' : '下载'}
                </span>
            </td>
            <td class="truncate-text" title="${historyItem.path}">${historyItem.path}</td>
        `;
        
        // 在表格顶部插入新行
        tbody.insertBefore(tr, tbody.firstChild);
        
        // 移除超过1分钟的记录
        const rows = tbody.getElementsByTagName('tr');
        for (let i = rows.length - 1; i >= 0; i--) {
            const row = rows[i];
            if (row.classList.contains('sync-record')) {
                const timestamp = new Date(row.dataset.timestamp);
                if (now - timestamp > 60000) { // 60000毫秒 = 1分钟
                    tbody.removeChild(row);
                }
            }
        }

        // 如果没有记录，显示"暂无同步记录"
        if (tbody.children.length === 0) {
            const tr = document.createElement('tr');
            tr.innerHTML = '<td colspan="5" class="text-center text-muted">暂无同步记录</td>';
            tbody.appendChild(tr);
        }

        // 移除新项目的动画类
        setTimeout(() => {
            tr.classList.remove('new-sync-item');
        }, 500);
    });

    // 监听同步状态更新
    socket.on('sync_status', function(data) {
        console.log('收到同步状态更新:', data);
        const statusBadge = document.querySelector(`#sync-status-${data.sync_dir_id}`);
        if (statusBadge) {
            statusBadge.className = `badge ${getStatusClass(data.status)}`;
            statusBadge.textContent = data.status;
        }
    });
}

// 重连调度函数
function scheduleReconnect() {
    if (!reconnectTimer) {
        console.log('计划5秒后重新连接...');
        reconnectTimer = setTimeout(() => {
            reconnectTimer = null;
            if (!socket || !socket.connected) {
                console.log('执行重新连接...');
                initializeSocket();
            }
        }, 5000);
    }
}

// 获取操作类型对应的样式类
function getOperationClass(operation) {
    const classMap = {
        'create': 'bg-success',
        'create_dir': 'bg-success',
        'delete': 'bg-danger',
        'delete_dir': 'bg-danger',
        'modify': 'bg-warning',
        'move': 'bg-info',
        'move_dir': 'bg-info',
        'upload': 'bg-success',
        'download': 'bg-info'
    };
    return classMap[operation] || 'bg-secondary';
}

// 获取状态对应的样式类
function getStatusClass(status) {
    const classMap = {
        'active': 'bg-success',
        'syncing': 'bg-primary',
        'error': 'bg-danger',
        'pending': 'bg-warning'
    };
    return classMap[status] || 'bg-secondary';
}

// 页面加载完成后初始化WebSocket
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，初始化WebSocket连接...');
    initializeSocket();
    
    // 过滤初始记录
    const now = new Date();
    document.querySelectorAll('.sync-record').forEach(record => {
        const timestamp = new Date(record.dataset.timestamp);
        if (now - timestamp > 60000) { // 60000毫秒 = 1分钟
            record.remove();
        }
    });

    // 检查每个表格体，如果没有记录则显示"暂无同步记录"
    document.querySelectorAll('.sync-group tbody').forEach(tbody => {
        if (tbody.children.length === 0) {
            const tr = document.createElement('tr');
            tr.innerHTML = '<td colspan="5" class="text-center text-muted">暂无同步记录</td>';
            tbody.appendChild(tr);
        }
    });
});

// 页面可见性变化时检查连接
document.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'visible') {
        console.log('页面变为可见，检查WebSocket连接...');
        if (!socket || !socket.connected) {
            console.log('WebSocket未连接，重新初始化...');
            initializeSocket();
        }
    }
});

// 定期检查连接状态
setInterval(function() {
    if (!socket || !socket.connected) {
        console.log('定期检查：WebSocket未连接，尝试重新连接...');
        initializeSocket();
    }
}, 30000);

function openStrategyModal(dirId) {
    currentDirId = dirId;
    const modal = document.getElementById('strategyModal');
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden';

    // 更新链接的href
    document.getElementById('local-priority-link').href = `/set_sync_strategy/${dirId}/local_priority`;
    document.getElementById('server-priority-link').href = `/set_sync_strategy/${dirId}/server_priority`;
    document.getElementById('time-size-link').href = `/set_sync_strategy/${dirId}/time_size`;
}

function closeStrategyModal() {
    const modal = document.getElementById('strategyModal');
    modal.style.display = 'none';
    document.body.style.overflow = '';
    currentDirId = null;
}

// 点击模态框外部关闭
window.onclick = function(event) {
    const modal = document.getElementById('strategyModal');
    if (event.target == modal) {
        closeStrategyModal();
    }
}
</script>

<style>
/* 统计卡片样式 */
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.stat-card {
    display: flex;
    align-items: center;
    background-color: white;
    border-radius: var(--border-radius);
    padding: 1rem;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    transition: transform 0.3s;
}

.stat-card:hover {
    transform: translateY(-3px);
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    margin-right: 1rem;
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--text-color);
    line-height: 1.2;
}

.stat-label {
    color: var(--text-secondary);
    font-size: 0.9rem;
}

/* 同步活动样式 */
.sync-activities {
    border-top: 1px solid #dee2e6;
    padding-top: 1.5rem;
}

.sync-activities h6 {
    margin-bottom: 1rem;
    color: var(--text-color);
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.sync-group {
    margin-bottom: 2rem;
}

.sync-group:last-child {
    margin-bottom: 0;
}

.sync-group-header {
    padding: 0.75rem 1rem;
    background-color: #f8f9fa;
    border-radius: var(--border-radius);
    margin-bottom: 1rem;
}

.sync-group-header h6 {
    margin: 0;
    color: var(--text-color);
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.sync-group .table {
    margin-bottom: 0;
}

.truncate-text {
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 新同步项目动画 */
.new-sync-item {
    animation: slideDown 0.5s ease-out;
    background-color: rgba(var(--primary-rgb), 0.1);
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 动画效果 */
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.fade-in {
    animation: fadeIn 0.3s ease-out;
}

tr {
    transition: background-color 0.3s;
}

tr:hover {
    background-color: rgba(0,0,0,0.02);
}

/* 响应式调整 */
@media (max-width: 768px) {
    .stats-container {
        grid-template-columns: 1fr;
    }

    .table-responsive {
        margin: 0 -1rem;
    }

    .truncate-text {
        max-width: 150px;
    }
}

.strategy-btn {
    padding: 0.5rem 1rem;
    border: 1px solid #dee2e6;
    background: white;
    border-radius: var(--border-radius);
    cursor: pointer;
    transition: all 0.3s;
}

.strategy-btn:hover {
    opacity: 0.8;
}

.strategy-btn .badge {
    font-size: 1rem;
    padding: 0.6rem 1rem;
}

/* 状态徽章样式 */
td .badge {
    font-size: 1rem;
    padding: 0.6rem 1rem;
}

/* 模态框样式 */
.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1050;
    animation: fadeIn 0.2s ease-out;
}

.modal-content {
    position: relative;
    background-color: #fff;
    margin: 10vh auto;
    width: 90%;
    max-width: 600px;  /* 增加模态框宽度 */
    border-radius: var(--border-radius);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    animation: slideIn 0.3s ease-out;
}

.modal-header {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #dee2e6;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.modal-header h4 {
    margin: 0;
    color: var(--text-color);
}

.close-modal {
    font-size: 1.5rem;
    font-weight: 700;
    color: #666;
    cursor: pointer;
    padding: 0.5rem;
    margin: -0.5rem;
}

.close-modal:hover {
    color: #333;
}

.modal-body {
    padding: 1.5rem;
}

.strategy-options {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.strategy-option {
    display: flex;
    align-items: center;
    padding: 1rem;
    border: 1px solid #dee2e6;
    border-radius: var(--border-radius);
    text-decoration: none;
    color: var(--text-color);
    transition: all 0.3s;
}

.strategy-option:hover {
    border-color: var(--primary-color);
    background-color: #f8f9fa;
    transform: translateY(-2px);
}

.strategy-icon {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background-color: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    margin-right: 1rem;
}

.strategy-info {
    flex: 1;
}

.strategy-info .badge {
    font-size: 1.1rem;
    padding: 0.6rem 1.2rem;
}

.strategy-info p {
    margin: 0.5rem 0 0 0;
    color: var(--text-secondary);
    font-size: 1rem;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideIn {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
{% endblock %}